import Cookie from 'js-cookie'
export const state = () => ({
  contentData: [],
  pageSize: 10,
  pageNum: 0,
  contentLoading: '4', // 1 加载更多 2 正在加载 3 没有更多了 4 初始化显示
  keywords: ''
})

export const mutations = {
  SET_CONTENT_DATA: function (state, contentData) {
    state.contentData = contentData
  },
  SET_KEYWORDS: function (state, keywords) {
    state.keywords = keywords
  },
  SET_CONTENT_LOADING: function (state, contentLoading) {
    state.contentLoading = contentLoading
  },
  SET_PAGE_NUM: function (state, pageNum) {
    state.pageNum = pageNum
  }
}

export const actions = {
  // oper 判断 请求的方式 是 浏览器回退、点击加载更多、访问url初始化数据
  getContentData ({commit}, {oper, keywords}) {
    let that = this
    let pageNum = that.state.content_search.pageNum
    // 点击分页
    if (oper === 'more') {
      pageNum = pageNum + 1
      commit('SET_PAGE_NUM', pageNum)
    } else {
      pageNum = 1
      commit('SET_PAGE_NUM', pageNum)
    }
    // 改变为加载状态
    commit('SET_CONTENT_LOADING', '2')
    let result = that.state.content_search.contentData
    that.$axios.post('/content/getList/' + that.state.content_search.pageSize + '/' + that.state.content_search.pageNum, {
      keywords: keywords
    }).then(function (data) {
      let _d = data.data.list
      if (_d === null || _d === undefined) {
        _d = []
      }
      if (result === null || result === undefined) {
        result = []
      }
      if (oper === 'more') {
        result = result.concat(_d)
      } else {
        result = _d
      }
      commit('SET_CONTENT_DATA', result)
      let _loading = '1'
      if (data.data.isLastPage) {
        _loading = '3'
      }
      commit('SET_CONTENT_LOADING', _loading)
    }).catch(function (err) {
      console.log(err)
    })
  },
  setKeywords ({commit}, {keywords}) {
    commit('SET_KEYWORDS', keywords)
  }
}
